package com.dp.service.impl3;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dp.pojo.JsonPage;
import com.dp.pojo.NewsVo;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.vo.NewsExtendsFirstchannel;
import com.dp.vo.NewsK16Menu;
import com.dp.vo.NewsK16server;
import com.dp.vo.TChannels;
import com.dp.vo.THdTags;
import com.dp.vo.THdTagsHdContents;

@Service
@Transactional
public class HdTagsServiceImpl extends BaseImpl {
	
	/**
	 * Find all the THdTags Entity
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<THdTags>
	 */
	public List<THdTags> findAllHdTagsEntity(DataMap hashMap, Integer firstrow,
			Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		THdTags hdtags=(THdTags) hashMap.get("hdtags");
		StringBuffer sqlS = new StringBuffer("SELECT t FROM THdTags t WHERE 1=1 ");
		if(hdtags!=null){
			if(hdtags.getTagname()!=null&& hdtags.getTagname().toString().trim().length() > 0){
				sqlS.append(" AND t.tagname like '%"
						+ hdtags.getTagname().toString().trim() + "%'");
			}
			if(hdtags.getChannel()!=null&&hdtags.getChannel().getChannelId()!=null&& hdtags.getChannel().getChannelId().toString().trim().length() > 0){
				sqlS.append(" AND t.channel.channelId='"
						+ hdtags.getChannel().getChannelId().toString().trim() + "'");
			}
		}
		
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sqlS.append(" order by t."+jpage.getSidx()+" "+jpage.getSord());
			}
		}
		List<THdTags> queryList=new ArrayList<THdTags>();
		try {
			Query query = em.createQuery(sqlS.toString());
			if (firstrow != null) {
				query.setFirstResult(firstrow);
			}
			if (maxrow != null) {
				query.setMaxResults(maxrow);
			}
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return queryList;
	}
	
	/**
	 * Portal标签 记录数
	 * @param hashMap
	 * @return Integer
	 */
	public Integer findAllHdTagsEntityCount(DataMap hashMap){
		THdTags hdtags=(THdTags) hashMap.get("hdtags");
		Integer iCount = 0; 
		StringBuffer sqlS = new StringBuffer("SELECT count(t.tid) FROM THdTags t WHERE 1=1 ");
		if(hdtags!=null){
			if(hdtags.getTagname()!=null&& hdtags.getTagname().toString().trim().length() > 0){
				sqlS.append(" AND t.tagname like '%"
						+ hdtags.getTagname().toString().trim() + "%'");
			}
			if(hdtags.getChannel()!=null&&hdtags.getChannel().getChannelId()!=null&& hdtags.getChannel().getChannelId().toString().trim().length() > 0){
				sqlS.append(" AND t.channel.channelId='"
						+ hdtags.getChannel().getChannelId().toString().trim() + "'");
			}
		}
		
		Query query=null;
		try {
			query = em.createQuery(sqlS.toString());
			iCount = Integer.valueOf(query.getSingleResult().toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return iCount;
	}

	/**
	 * 分类信息根栏目下一级栏目
	 * @param hdnews_rootch
	 * @return
	 */
	public List<TChannels> findfristHdchannels(String hdnews_rootch) {
		StringBuffer sqlS = new StringBuffer("SELECT t FROM TChannels t WHERE 1=1 and previous_id=:hdnews_rootch " +
				"AND channelType='"+BookConfig.channel_type_hdnews+"' and channelClassifyingLabel is not null");
		List<TChannels> queryList=new ArrayList<TChannels>();
		try {
			Query query = em.createQuery(sqlS.toString());
			query.setParameter("hdnews_rootch", hdnews_rootch);
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return queryList;
	}
	
	public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
			chList = queryALLResultSet(sql);
		} catch (Exception e) {
			log.info(" NewsServiceImpl3 buildChChildIdAndPreviousIdMap fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
	
	private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null)&& !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }

	//新增
	public Boolean addHdagsE(THdTags hdtags) {
		Boolean resultb=true;
		try {
			String jpql="SELECT t FROM THdTags t WHERE t.tagname=:tagname and t.channel.channelId=:channelId";
			Query query = em.createQuery(jpql);
			query.setParameter("tagname",hdtags.getTagname());
			query.setParameter("channelId",hdtags.getChannel().getChannelId());
			THdTags hdtags_temp= (THdTags) getSingleResult(query);
			if(hdtags_temp!=null){
				resultb=null;
			}else{
				em.persist(hdtags);
			}
		} catch (Exception e) {
			logger.error("addHdagsE fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		} 
		return resultb;
	}
	
	//修改
	public Boolean updateHdagsE(THdTags hdtags) {
		Boolean resultb=true;
		try {
			String jpql="SELECT t FROM THdTags t WHERE t.tagname=:tagname and t.channel.channelId=:channelId and t.tid=:tid";
			Query query = em.createQuery(jpql);
			query.setParameter("tagname",hdtags.getTagname());
			query.setParameter("channelId",hdtags.getChannel().getChannelId());
			query.setParameter("tid",hdtags.getTid());
			THdTags hdtags_temp= (THdTags) getSingleResult(query);
			if(hdtags_temp==null){
				jpql="UPDATE THdTags t SET t.tagname=:tagname,t.channel.channelId=:channelId WHERE t.tid=:tid";
				query = em.createQuery(jpql);
				query.setParameter("tagname",hdtags.getTagname());
				query.setParameter("channelId",hdtags.getChannel().getChannelId());
				query.setParameter("tid",hdtags.getTid());
				query.executeUpdate();
			}
		} catch (Exception e) {
			logger.error("updateK16serverE fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		}
		return resultb;
	}
	
	//删除
	public Boolean deleteHdagsEByIds(String ids) {
		Boolean resultb=true;
//		try {
//			this.init();
//			String[] idarys=ids.split(",");
//			this.sql="delete from t_hdtags_hdcontents where tid=?";
//			prep=conn.prepareStatement(sql);	
//				sql="delete from t_hdtags where tid=?";
//			prep1=conn.prepareStatement(sql);
//			for(String id:idarys){
//				prep.setString(1, id);
//				prep.addBatch();
//				prep1.setString(1, id);
//				prep1.addBatch();
//			}
//			prep.executeBatch();
//			prep1.executeBatch();
//			conn.commit(); 
//			this.closeAll();
//		} catch (Exception e) {
//			logger.error("deleteK16serverEByIds fail !!!" + e.getMessage());
//			e.printStackTrace();
//			resultb=false;
//			if(conn!=null){
//				try {
//					conn.rollback();
//				} catch (SQLException e1) {
//					e1.printStackTrace();
//				} 
//			}
//		} finally {
//			this.closeAll();
//		}
		return resultb;
	}
	
	//标签下内容排序
	public List<THdTagsHdContents> contentSortById(Integer tid) {
		StringBuffer sqlS = new StringBuffer("SELECT t FROM THdTagsHdContents t WHERE 1=1 and tHdTagsHdContentsPK.hdtag.tid=:tid");
		List<THdTagsHdContents> queryList=new ArrayList<THdTagsHdContents>();
		try {
			
			Query query = em.createQuery(sqlS.toString());
			query.setParameter("tid", tid);
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return queryList;
	}
	
	public boolean sortCids(Integer tid, String selectcids) {
		Boolean resultb=true;
//		try {
//			if(selectcids!=null && !selectcids.equals(""))
//	        {
//	        	this.init();
//	        	this.sql = "update t_hdtags_hdcontents  set tc_order=? where tid=? and cid=?";
//				this.prep=this.conn.prepareStatement(sql);
//		    	String[] c_id_strList=selectcids.split(",");
//		    	for(int i=0;i<c_id_strList.length;i++)
//		        {
//		    		int cid = Integer.parseInt(c_id_strList [i]) ;
//					prep.setInt(1, i+1);
//					prep.setInt(2, tid);
//					prep.setInt(3, cid);
//					prep.addBatch();
//		        }
//		    	prep.executeBatch();
//		    	conn.commit(); 
//		    	this.closeAll();
//	        }
//		} catch (Exception e) {
//			logger.info("sortCids fail !!!" + e.getMessage());
//			e.printStackTrace();
//			resultb=false;
//		}
		return resultb;
	}
	
	public Object getSingleResult(Query query) {
		Object o =null;
		try {
			o = query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		} catch (NonUniqueResultException ex) {
			o = query.getResultList();
			return ((List) o).get(0);
		}
		return o;
	}
}
